package com.example.iwalk.newprintapplication.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.example.iwalk.newprintapplication.R;
import com.example.iwalk.newprintapplication.adapter.IpAddressAdapter;
import com.example.iwalk.newprintapplication.imp.NetSocket;
import com.example.iwalk.newprintapplication.imp.Printer80Imp;
import com.example.iwalk.newprintapplication.inter.AdapterButtonClickListener;
import com.example.iwalk.newprintapplication.inter.IpCatcher;
import com.example.iwalk.newprintapplication.inter.Printer;
import com.example.iwalk.newprintapplication.inter.SocketInter;
import com.example.iwalk.newprintapplication.inter.SocketStateChangeListener;
import com.example.iwalk.newprintapplication.util.BytesUtil;
import com.example.iwalk.newprintapplication.util.ESCUtil;
import com.example.iwalk.newprintapplication.util.IpCatchThread;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import static com.example.iwalk.newprintapplication.constant.SocketState.ERROR_0;
import static com.example.iwalk.newprintapplication.constant.SocketState.ERROR_1;
import static com.example.iwalk.newprintapplication.constant.SocketState.ERROR_2;
import static com.example.iwalk.newprintapplication.constant.SocketState.ERROR_3;
import static com.example.iwalk.newprintapplication.constant.SocketState.ERROR_4;
import static com.example.iwalk.newprintapplication.constant.SocketState.ERROR_5;
import static com.example.iwalk.newprintapplication.constant.SocketState.STATE_1;
import static com.example.iwalk.newprintapplication.constant.SocketState.STATE_2;
import static com.example.iwalk.newprintapplication.constant.SocketState.STATE_3;
import static com.example.iwalk.newprintapplication.constant.SocketState.STATE_4;
import static com.example.iwalk.newprintapplication.constant.SocketState.STATE_41;
import static com.example.iwalk.newprintapplication.constant.SocketState.STATE_5;

public class IpCatcherActivity extends AppCompatActivity implements AdapterButtonClickListener, View.OnClickListener {
    private static final String CHARSET = "gbk";
    private TextView tv_ip, tv_printer_info, tv_socket_info;
    private ListView lv_ip_address;
    private List<String> ipAddresses;
    private IpAddressAdapter adapter;
    private Button btn_catch;
    SocketStateChangeListener stateChangeListener = new SocketStateChangeListener() {
        @Override
        public void onStateChanged(final int state) {
            tv_socket_info.post(new Runnable() {
                @Override
                public void run() {
                    switch (state) {
                        case STATE_1:
                            tv_socket_info.setText("正在创建Socket连接");
                            break;
                        case STATE_2:
                            tv_socket_info.setText("正在获取输出流");
                            break;
                        case STATE_3:
                            tv_socket_info.setText("正在写入测试页面数据");
                            break;
                        case STATE_4:
                            tv_socket_info.setText("正在关闭输出流");
                            break;
                        case STATE_41:
                            tv_socket_info.setText("关闭输出流成功");
                            break;
                        case STATE_5:
                            tv_socket_info.setText("正在获取输入流");
                            break;
                    }
                }
            });
        }

        @Override
        public void onConnectFailed(final int error) {
            tv_socket_info.post(new Runnable() {
                @Override
                public void run() {
                    switch (error) {
                        case ERROR_0:
                            tv_socket_info.setText("必要参数不能为空");
                            break;
                        case ERROR_1:
                            tv_socket_info.setText("创建Socket失败");
                            break;
                        case ERROR_2:
                            tv_socket_info.setText("获取输出流失败");
                            break;
                        case ERROR_3:
                            tv_socket_info.setText("写入测试页面数据失败");
                            break;
                        case ERROR_4:
                            tv_socket_info.setText("关闭Socket出错");
                            break;
                        case ERROR_5:
                            tv_socket_info.setText("获取输出流失败");
                            break;
                    }
                }
            });
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ip_catcher);
        initView();
    }

    private void initView() {
        btn_catch = (Button) findViewById(R.id.btn_catch);
        tv_ip = ((TextView) findViewById(R.id.text));
        tv_socket_info = ((TextView) findViewById(R.id.tv_socket_info));
        tv_printer_info = ((TextView) findViewById(R.id.tv_printer_info));
        lv_ip_address = ((ListView) findViewById(R.id.listview));
        ipAddresses = new ArrayList<>();
        adapter = new IpAddressAdapter(ipAddresses, this);
        adapter.setListener(this);
        lv_ip_address.setAdapter(adapter);
        btn_catch.setOnClickListener(this);
    }

    @Override
    public void onButtonClick(int position, View view) {
        NetPrintThreadStart(ipAddresses.get(position));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_catch:
                String localHostIp = NetSocket.getLocalHostIp();
                tv_ip.setText(localHostIp);
                new IpCatchThread(localHostIp, new IpCatcher() {
                    @Override
                    public void onCatchStart() {
                        lv_ip_address.post(new Runnable() {
                            @Override
                            public void run() {
                                btn_catch.setText("正在获取打印机列表");
                                ipAddresses.clear();
                                adapter.notifyDataSetChanged();
                            }
                        });
                    }

                    @Override
                    public void onIpCatched(final String ipAddress) {
                        lv_ip_address.post(new Runnable() {
                            @Override
                            public void run() {
                                ipAddresses.add(ipAddress);
                                adapter.notifyDataSetChanged();
                            }
                        });
                    }

                    @Override
                    public void onCatchFinish() {
                        btn_catch.post(new Runnable() {
                            @Override
                            public void run() {
                                btn_catch.setText("打印机列表获取完毕，点击重新获取");
                            }
                        });
                    }
                }).start();
                break;
        }
    }

    private void NetPrintThreadStart(final String host) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SocketInter socketInter =
                        new NetSocket(host, 9100, stateChangeListener);
                Printer printer = new Printer80Imp();
//                Operator operator = new OperatorImp("gb2312");
//                printer.print(socketInter.getSocketOut(), operator.getPrinterInfo(), stateChangeListener);
                try {
                    printer.print(socketInter.getSocketOut(), getAlignData(printer), stateChangeListener);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
//                Log.e("sdsdf", "(socketInter.getSocketOut");
//                InputStream inputStream = socketInter.getSocketIn();
//                Log.e("sdsdf", "socketInter.getSocketIn");
//                while (true) {
//                    try {
//                        String s = inputStream2String(inputStream);
//                        Message msg = handler.obtainMessage();
//                        msg.what = 11;
//                        msg.obj = s;
//                        handler.sendMessage(msg);
//                        if (!s.equals("")) {
//                            break;
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
                socketInter.close();
            }
        }).start();
    }

    private byte[] getAlignData(Printer printer) throws UnsupportedEncodingException {
        String alignString = PrintActivity.getAlignString(printer);
        byte[] threeData4 = alignString.getBytes(CHARSET);
        byte[] threeData5 = PrintActivity.getAlignStrByLine(printer).getBytes(CHARSET);
        byte[] threeData6 = PrintActivity.getAlignStrByLine2(printer).getBytes(CHARSET);
        byte[] threeData7 = PrintActivity.getAlignStrByLine3(printer).getBytes(CHARSET);
        byte[] threeData8 = "一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十".getBytes(CHARSET);
//        byte[] endData = socketType == SocketInter.TYPE_NET ? ESCUtil.feedPaperCutPartial() : ESCUtil.nextLine(2);
        return ESCUtil.byteMerger(
                new byte[][]{ESCUtil.init_printer(),
                        ESCUtil.setLineSp(0),
                        ESCUtil.boldOn(),
//                        twoData, ESCUtil.nextLine(1),
//                        threeData, ESCUtil.nextLine(1),
//                        threeData2, ESCUtil.nextLine(1),
                        threeData5, ESCUtil.nextLine2(1),
                        ESCUtil.boldOff(),
                        threeData6, ESCUtil.nextLine2(1),
                        threeData7, ESCUtil.nextLine2(1),
                        getBitmapData(printer), ESCUtil.nextLine2(1),
                        getQrCodeData(printer), ESCUtil.nextLine2(1),
                        threeData8, ESCUtil.nextLine2(1), ESCUtil.feedPaperCutPartial()});
    }

    public byte[] getBitmapData(Printer printer) {
        byte[] align = new byte[3];
//        if (rb_left.isChecked()) {
//            align = ESCUtil.alignLeft();
//        } else if (rb_center.isChecked()) {
//            align = ESCUtil.alignCenter();
//        } else if (rb_right.isChecked()) {
//            align = ESCUtil.alignRight();
//        }

        Bitmap bitmap = ESCUtil.
                compressPic(BitmapFactory.decodeResource(getResources(), R.mipmap.test),
                        printer.getDrawableMaxWidth() / 2, printer.getDrawableMaxWidth() / 2);
//                        288, 288);
        boolean needLF = true;
//        boolean needLF = socketType == SocketInter.TYPE_NET ? true : false;
        byte[] bitmapData = ESCUtil.draw2PxPoint(bitmap, needLF);
//        byte[] bitmapData =  ESCUtil.draw2PxPoint(BitmapFactory.decodeResource(getResources(), R.mipmap.test), needLF);

        return ESCUtil.byteMerger(
                new byte[][]{ESCUtil.init_printer(), ESCUtil.nextLine(2),
                        align, ESCUtil.setLineSp(0), bitmapData});
    }

    public byte[] getQrCodeData(Printer printer) {
        String qr_data = "";
        if (qr_data.equals("")) {
            qr_data = "http://www.baidu.com";
        }
        return BytesUtil.getZXingQRCode(
                qr_data, printer.getDrawableMaxWidth() / 2);
    }
}
